import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';

class MyShouYiPage extends StatefulWidget {
  @override
  _MyShouYiPageState createState() => _MyShouYiPageState();
}

class _MyShouYiPageState extends State<MyShouYiPage> {
  String token = "", num10 = "", num11 = "", num12 = "";
  String group_name = "", userName = "", avatar;
  String time1 = "", time3 = "";
  final Color leftBarColor = const Color(0xff53fdd7);
  // final Color rightBarColor = const Color(0xffff5182);
  final double width = 7;

  List<BarChartGroupData> rawBarGroups = new List();
  List<BarChartGroupData> showingBarGroups = new List();
  List<BarChartGroupData> dayrawBarGroups = new List();
  List<BarChartGroupData> dayshowingBarGroups = new List();
  List<String> monthX = new List();
  List<String> monthValue = new List();
  List<String> dayX = new List();
  List<String> dayValue = new List();
  double monthMax = 0, dayMax = 0;
  int touchedGroupIndex;

  @override
  void initState() {
    super.initState();
    var today = DateTime.now();
    time1 = DateUtils.instance.getFormartData(
        timeSamp: today.millisecondsSinceEpoch, format: "yyyy-MM");
    time3 = DateUtils.instance
        .getFormartData(timeSamp: today.millisecondsSinceEpoch, format: "yyyy");
    group_name = APPLIC.userInfoMap['user_msg']['group_name'];
    userName = APPLIC.userInfoMap['user_detail']['nickname'] == null
        ? APPLIC.userInfoMap['user_msg']['phone']
        : APPLIC.userInfoMap['user_detail']['nickname'];
    avatar = APPLIC.userInfoMap['user_detail']['avatar'];
    getString(TOKEN).then((value) {
      token = value;
      getTuiguang();
      loadList();
      loadList2();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['month'] = time1;
    map['year'] = time3;
    map['sign_type'] = SignType.GETPROFIT;
    print(map);
    Response<String> response =
        await HttpUtil().post(Api.GETPROFIT, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      int count = 0;
      dayrawBarGroups.clear();
      dayshowingBarGroups.clear();
      (userMap['data']['month'] as List).forEach((v) {
        dayX.add(v['create_time'].toString().split("-")[2].split(" ")[0]);
        dayValue.add(double.parse(v['profit'].toString()).floor().toString());
        if (count == 0) {
          dayMax = double.parse(v['profit'].toString());
        } else {
          if (dayMax < double.parse(v['profit'].toString())) {
            dayMax = double.parse(v['profit'].toString());
          }
        }
        dayrawBarGroups
            .add(makeGroupData(count, double.parse(v['profit'].toString())));
        dayshowingBarGroups
            .add(makeGroupData(count, double.parse(v['profit'].toString())));
        count = count + 1;
      });
      setState(() {});
    }
  }

  loadList2() async {
    Map map = new Map();
    map['token'] = token;
    map['month'] = time1;
    map['year'] = time3;
    map['sign_type'] = SignType.GETPROFIT;
    Response<String> response =
        await HttpUtil().post(Api.GETPROFIT, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      int count = 0;
      rawBarGroups.clear();
      showingBarGroups.clear();
      (userMap['data']['year'] as List).forEach((v) {
        monthX.add(v['create_time'].toString().split("-")[1]);
        monthValue.add(double.parse(v['profit'].toString()).floor().toString());
        if (count == 0) {
          monthMax = double.parse(v['profit'].toString());
        } else {
          if (monthMax < double.parse(v['profit'].toString())) {
            monthMax = double.parse(v['profit'].toString());
          }
        }
        rawBarGroups
            .add(makeGroupData(count, double.parse(v['profit'].toString())));
        showingBarGroups
            .add(makeGroupData(count, double.parse(v['profit'].toString())));
        count = count + 1;
      });
      setState(() {});
    }
  }

  getTuiguang() async {
    Map map = new Map();
    map['token'] = token;
    map['sign_type'] = SignType.GET_USER_TUIGUANG;
    Response<String> response =
        await HttpUtil().post(Api.GET_USER_TUIGUANG, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      num10 = userMap['data']['profit']['allprofit'].toString();
      num11 = userMap['data']['profit']['m_profit'].toString();
      num12 = userMap['data']['profit']['y_profit'].toString();
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '我的收益',
          style: TextStyle(
              color: black,
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
        ),
        backgroundColor: white,
        brightness: Brightness.light,
        elevation: 0.5,
        iconTheme: IconThemeData(color: black_99),
      ),
      body: new Container(
          color: white,
          width: double.infinity,
          padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
          child: Column(children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  child: ClipOval(
                    child: avatar == null
                        ? Image.asset(
                            "images/app_icon.png",
                            fit: BoxFit.cover,
                            width: ScreenUtil.getInstance().setWidth(80),
                            height: ScreenUtil.getInstance().setWidth(80),
                          )
                        : CachedNetworkImage(
                imageUrl:
                            avatar,
                            fit: BoxFit.cover,
                            width: ScreenUtil.getInstance().setWidth(80),
                            height: ScreenUtil.getInstance().setWidth(80),
                          ),
                  ),
                  onTap: () {},
                ),
                Container(
                  width: DP_15,
                ),
                Text(userName,
                    style: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                        color: Colors.black)),
                Container(
                  width: DP_15,
                ),
                Text(
                  group_name,
                  style: TextStyle(
                      fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                      color: black),
                ),
                Expanded(
                  child: Center(),
                ),
              ],
            ),
            Container(
              height: DP_15,
            ),
            Row(
              children: <Widget>[
                Expanded(child: Center()),
                Text('总收益: ',
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: ScreenUtil.getInstance()
                            .setSp(SMALL_FONT_SIZE - 1))),
                Text('$num10',
                    style: TextStyle(
                        color: mainColor,
                        fontSize:
                            ScreenUtil.getInstance().setSp(BIG_FONT_SIZE - 4))),
                Expanded(child: Center()),
                Text('昨日收益: ',
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: ScreenUtil.getInstance()
                            .setSp(SMALL_FONT_SIZE - 1))),
                Text('$num12',
                    style: TextStyle(
                        color: black,
                        fontSize:
                            ScreenUtil.getInstance().setSp(BIG_FONT_SIZE - 4))),
                Expanded(child: Center()),
                Text('本月收益: ',
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: ScreenUtil.getInstance()
                            .setSp(SMALL_FONT_SIZE - 1))),
                Text('$num11',
                    style: TextStyle(
                        color: black,
                        fontSize:
                            ScreenUtil.getInstance().setSp(BIG_FONT_SIZE - 4))),
                Expanded(child: Center()),
              ],
            ),
            Container(
              height: ScreenUtil.getInstance().setHeight(1),
              margin: EdgeInsets.only(top: 15, bottom: 15),
              color: f0Color,
            ),
            Row(
              children: <Widget>[
                Text('日收益统计',
                    style: TextStyle(
                        color: black,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
                Expanded(child: Center()),
                GestureDetector(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                    decoration: BoxDecoration(
                        border: Border.all(color: mainColor, width: 1),
                        borderRadius: BorderRadius.circular(3)),
                    child: Row(children: <Widget>[
                      Text('$time1',
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Icon(
                        Icons.arrow_drop_down,
                        color: mainColor,
                      )
                    ]),
                  ),
                  onTap: () {
                    DatePicker.showDatePicker(context,
                        pickerTheme: DateTimePickerTheme(
                          showTitle: true,
                          confirm:
                              Text('确定', style: TextStyle(color: Colors.red)),
                          cancel:
                              Text('取消', style: TextStyle(color: Colors.cyan)),
                        ),
                        minDateTime: DateTime.parse("1980-05-01"),
                        dateFormat: "yyyy-MM",
                        pickerMode: DateTimePickerMode.date,
                        locale: DateTimePickerLocale.zh_cn, onCancel: () {
                      debugPrint("onCancel");
                    }, onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        time1 = DateUtils.instance.getFormartData(
                            timeSamp: dateTime.millisecondsSinceEpoch,
                            format: "yyyy-MM");
                        loadList();
                      });
                    });
                  },
                ),
              ],
            ),
            Container(
              height: 20,
            ),
            Expanded(
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(horizontal: 15.0),
                child: ListView.builder(
                  itemCount: 1,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      padding: EdgeInsets.only(left: 20),
                      child: BarChart(
                        BarChartData(
                          maxY: dayMax + 20,
                          barTouchData: BarTouchData(
                              touchTooltipData: BarTouchTooltipData(
                                // tooltipBgColor: Colors.grey,
                                tooltipBottomMargin: 0,
                                tooltipPadding: EdgeInsets.all(0),
                                getTooltipItem: (
                                  BarChartGroupData group,
                                  int groupIndex,
                                  BarChartRodData rod,
                                  int rodIndex,
                                ) {
                                  return BarTooltipItem(
                                    rod.y.round().toString(),
                                    TextStyle(
                                      color: mainColor,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(SMALL_FONT_SIZE),
                                    ),
                                  );
                                },
                              ),
                              touchCallback: (response) {
                                if (response.spot == null) {
                                  setState(() {
                                    touchedGroupIndex = -1;
                                    dayshowingBarGroups =
                                        List.of(dayrawBarGroups);
                                  });
                                  return;
                                }

                                touchedGroupIndex =
                                    response.spot.touchedBarGroupIndex;

                                setState(() {
                                  if (response.touchInput is FlLongPressEnd ||
                                      response.touchInput is FlPanEnd) {
                                    touchedGroupIndex = -1;
                                    dayshowingBarGroups =
                                        List.of(dayrawBarGroups);
                                  } else {
                                    dayshowingBarGroups =
                                        List.of(dayrawBarGroups);
                                    if (touchedGroupIndex != -1) {
                                      double sum = 0;
                                      for (BarChartRodData rod
                                          in dayshowingBarGroups[
                                                  touchedGroupIndex]
                                              .barRods) {
                                        sum += rod.y;
                                      }
                                      final avg = sum /
                                          dayshowingBarGroups[touchedGroupIndex]
                                              .barRods
                                              .length;

                                      dayshowingBarGroups[touchedGroupIndex] =
                                          dayshowingBarGroups[touchedGroupIndex]
                                              .copyWith(
                                        barRods: dayshowingBarGroups[
                                                touchedGroupIndex]
                                            .barRods
                                            .map((rod) {
                                          return rod.copyWith(y: avg);
                                        }).toList(),
                                      );
                                    }
                                  }
                                });
                              }),
                          titlesData: FlTitlesData(
                            show: true,
                            bottomTitles: SideTitles(
                              showTitles: true,
                              textStyle: TextStyle(
                                  color: const Color(0xff7589a2),
                                 fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE-3),),
                              margin: 5,
                              getTitles: (double value) {
                                return dayX[value.toInt()];
                              },
                            ),
                            leftTitles: SideTitles(
                              showTitles: false,
                              textStyle: TextStyle(
                                  color: const Color(0xff7589a2),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 14),
                              margin: 20,
                              reservedSize: 14,
                              getTitles: (value) {
                                if (value == 0) {
                                  return '0';
                                } else if (value ==
                                    1 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    2 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    3 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    4 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    5 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    6 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    7 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    8 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else if (value ==
                                    9 * ((dayMax / 10).floor())) {
                                  return value.toInt().toString();
                                } else {
                                  return '';
                                }
                              },
                            ),
                          ),
                          borderData: FlBorderData(
                            show: false,
                          ),
                          barGroups: dayshowingBarGroups,
                        ),
                      ),
                      width: 30 * ScreenUtil.getInstance().setWidth(DP_50),
                    );
                  },
                ),
              ),
            ),
            Container(
              height: 20,
            ),
            Row(
              children: <Widget>[
                Text('月收益统计',
                    style: TextStyle(
                        color: black,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
                Expanded(child: Center()),
                GestureDetector(
                  child: Container(
                    padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                    decoration: BoxDecoration(
                        border: Border.all(color: mainColor, width: 1),
                        borderRadius: BorderRadius.circular(3)),
                    child: Row(children: <Widget>[
                      Text('$time3',
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                      Icon(
                        Icons.arrow_drop_down,
                        color: mainColor,
                      )
                    ]),
                  ),
                  onTap: () {
                    DatePicker.showDatePicker(context,
                        pickerTheme: DateTimePickerTheme(
                          showTitle: true,
                          confirm:
                              Text('确定', style: TextStyle(color: Colors.red)),
                          cancel:
                              Text('取消', style: TextStyle(color: Colors.cyan)),
                        ),
                        minDateTime: DateTime.parse("1980-05-01"),
                        dateFormat: "yyyy",
                        pickerMode: DateTimePickerMode.date,
                        locale: DateTimePickerLocale.zh_cn, onCancel: () {
                      debugPrint("onCancel");
                    }, onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        time3 = DateUtils.instance.getFormartData(
                            timeSamp: dateTime.millisecondsSinceEpoch,
                            format: "yyyy");
                        loadList();
                      });
                    });
                    // DatePicker.showDatePicker(context,
                    //     showTitleActions: true,
                    //     onChanged: (date) {}, onConfirm: (date) {
                    //   setState(() {
                    //     time3 = DateUtils.instance.getFormartData(
                    //         timeSamp: date.millisecondsSinceEpoch,
                    //         format: "yyyy");
                    //     loadList2();
                    //   });

                    //   // page = 1;
                    //   // loadList();
                    // }, currentTime: DateTime.now(), locale: LocaleType.zh);
                  },
                ),
              ],
            ),
            Container(
              height: 20,
            ),
            Expanded(
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(horizontal: 15.0),
                child: BarChart(
                  BarChartData(
                    maxY: monthMax + 10,
                    barTouchData: BarTouchData(
                        touchTooltipData: BarTouchTooltipData(
                          // tooltipBgColor: Colors.grey,
                          tooltipPadding: EdgeInsets.all(0),
                          tooltipBottomMargin: 0,
                          getTooltipItem: (
                            BarChartGroupData group,
                            int groupIndex,
                            BarChartRodData rod,
                            int rodIndex,
                          ) {
                            return BarTooltipItem(
                              rod.y.round().toString(),
                              TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE),
                              ),
                            );
                          },
                        ),
                        touchCallback: (response) {
                          if (response.spot == null) {
                            setState(() {
                              touchedGroupIndex = -1;
                              showingBarGroups = List.of(rawBarGroups);
                            });
                            return;
                          }

                          touchedGroupIndex =
                              response.spot.touchedBarGroupIndex;

                          setState(() {
                            if (response.touchInput is FlLongPressEnd ||
                                response.touchInput is FlPanEnd) {
                              touchedGroupIndex = -1;
                              showingBarGroups = List.of(rawBarGroups);
                            } else {
                              showingBarGroups = List.of(rawBarGroups);
                              if (touchedGroupIndex != -1) {
                                double sum = 0;
                                for (BarChartRodData rod
                                    in showingBarGroups[touchedGroupIndex]
                                        .barRods) {
                                  sum += rod.y;
                                }
                                final avg = sum /
                                    showingBarGroups[touchedGroupIndex]
                                        .barRods
                                        .length;

                                showingBarGroups[touchedGroupIndex] =
                                    showingBarGroups[touchedGroupIndex]
                                        .copyWith(
                                  barRods: showingBarGroups[touchedGroupIndex]
                                      .barRods
                                      .map((rod) {
                                    return rod.copyWith(y: avg);
                                  }).toList(),
                                );
                              }
                            }
                          });
                        }),
                    titlesData: FlTitlesData(
                      show: true,
                      bottomTitles: SideTitles(
                        showTitles: true,
                        textStyle: TextStyle(
                            color: const Color(0xff7589a2),
                          fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE-3),),
                        margin: 5,
                        getTitles: (double value) {
                          return monthX[value.toInt()].toString();
                        },
                      ),
                      leftTitles: SideTitles(
                        showTitles: false,
                        textStyle: TextStyle(
                            color: const Color(0xff7589a2),
                             fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE),
                            ),
                        margin: 20,
                        reservedSize: 14,
                        getTitles: (value) {
                          if (value == 0) {
                            return '0';
                          } else if (value == (monthMax / 3).toInt()) {
                            return value.toInt().toString();
                          } else if (value == 2 * ((monthMax / 3).toInt())) {
                            return value.toInt().toString();
                          } else if (value == 3 * ((monthMax / 3).toInt())) {
                            return value.toInt().toString();
                          } else {
                            return '';
                          }
                          // return monthValue[value.toInt()].toString();
                        },
                      ),
                    ),
                    borderData: FlBorderData(
                      show: false,
                    ),
                    barGroups: showingBarGroups,
                  ),
                ),
              ),
            ),
            Container(
              height: 20,
            ),
          ])),
    );
  }

  BarChartGroupData makeGroupData(int x, double y1) {
    return BarChartGroupData(barsSpace: 4, x: x, showingTooltipIndicators: [
      0
    ], barRods: [
      BarChartRodData(
          y: y1,
          color: Colors.red[300],
          borderRadius: BorderRadius.circular(2),
          width: ScreenUtil.getInstance().setWidth(DP_20)),
      // BarChartRodData(
      //   y: y2,
      //   color: rightBarColor,
      //   width: width,
      // ),
    ]);
  }

  Widget makeTransactionsIcon() {
    const double width = 4.5;
    const double space = 3.5;
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: width,
          height: 10,
          color: Colors.white.withOpacity(0.4),
        ),
        const SizedBox(
          width: space,
        ),
        Container(
          width: width,
          height: 28,
          color: Colors.white.withOpacity(0.8),
        ),
        const SizedBox(
          width: space,
        ),
        Container(
          width: width,
          height: 42,
          color: Colors.white.withOpacity(1),
        ),
        const SizedBox(
          width: space,
        ),
        Container(
          width: width,
          height: 28,
          color: Colors.white.withOpacity(0.8),
        ),
        const SizedBox(
          width: space,
        ),
        Container(
          width: width,
          height: 10,
          color: Colors.white.withOpacity(0.4),
        ),
      ],
    );
  }
}
